<template>
  <div class="LabelSelectCpm">
    <el-select
      :multiple="false"
      filterable
      remote
      remote-show-suffix
      reserve-keyword
      placeholder="输入关键词搜索"
      :remote-method="remoteMethod"
      :loading="loading"
      @change="selectChange"
    >
      <el-option
        v-for="item in options"
        :key="item[labelKey[1]]"
        :label="item[labelKey[0]]"
        :value="item[labelKey[1]]"
        style="margin-bottom: 20px"
      >
      </el-option>
      <el-pagination
        style="position: absolute; bottom: 0"
        :hide-on-single-page="true"
        layout="prev, pager, next"
        :total="total"
        small
        :page-size="size"
        @current-change="handleCurrentChange"
      />
    </el-select>
  </div>
</template>
<script setup lang="ts">
const prop = defineProps({
  labelKey: {
    type: Array<string>,
    default: () => {
      return ["label", "key"];
    },
  },
  loadData: {
    type: Function,
    default: () => null,
  },
  size: {
    type: Number,
    default: 2,
  },
  model: {
    type: Object,
    default: () => null,
  },
});

const labelKey = ref(prop.labelKey);
const loadData = reactive(prop.loadData);
const model = reactive(prop.model);
const emits = defineEmits(["selectCallback"]);
const size = ref(prop.size);
const loading = ref(false);
// select-options 数据源
const options = ref([]);
const total = ref(0);
// 分页控制
const requsetObj = reactive({
  pageIndex: 1,
  pageSize: size,
  keywords: "",
});

const handleCurrentChange = (page: number) => {
  requsetObj.pageIndex = page;
  remoteMethod(requsetObj.keywords);
};

/**
 * @param {string} query 输入的搜索关键词
 */
const remoteMethod = (query: string) => {
  loading.value = true;
  if (query) {
    /* 记录输入的关键词 */
    requsetObj.keywords = query;
  } else {
    requsetObj.keywords = "";
  }
  loadData(requsetObj).then((res: any) => {
    if (res.success) {
      options.value = res.data.list;
      total.value = res.data.total;
      loading.value = false;
    } else {
      ElMessage({
        type: "error",
        message: res.msg,
      });
    }
  });
};

const selectChange = (val: any) => {
  model.value = val;
  emits("selectCallback", val);
};

onMounted(() => {
  remoteMethod("");
});
</script>

<style scoped></style>
